package com.lill.support.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.lill.common.component.util.R;
import com.lill.support.annotation.OnceSubmit;

import java.util.Objects;

@RestControllerAdvice
public class CommonResponseBodyAdvice implements ResponseBodyAdvice<Object> {
	public Logger logger= LoggerFactory.getLogger(CommonResponseBodyAdvice.class);
	@Override
	public boolean supports(MethodParameter returnType,Class<? extends HttpMessageConverter<?>> converterType) {
		if(returnType.hasMethodAnnotation(OnceSubmit.class)){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType,
			MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType,
			ServerHttpRequest request, ServerHttpResponse response) {
		if(body==null){
			logger.error("操作过于频繁所调用的方法是-{}---原因:返回体body为null", Objects.requireNonNull(returnType.getMethod()).getName());
			body=R.error("操作过于频繁");

		}
		return body;
	}

}
